package commonClass.system;

import java.util.Enumeration;
import java.util.HashSet;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;

public final class LibraryLoader {
	public static final String JACOB_DLL_PATH = "jacob.dll.path";
	public static final String JACOB_DLL_NAME = "jacob.dll.name";
	public static final String JACOB_DLL_NAME_X86 = "jacob.dll.name.x86";
	public static final String JACOB_DLL_NAME_X64 = "jacob.dll.name.x64";
	public static final String DLL_NAME_MODIFIER_32_BIT = "x86";
	public static final String DLL_NAME_MODIFIER_64_BIT = "x64";

	public static void main(String args[]){
		loadJacobLibrary();
	}
	public static void loadJacobLibrary() {
		ResourceBundle resources = null;
		Set keys = new HashSet();
		try {
			resources = ResourceBundle.getBundle(LibraryLoader.class.getName(),
					Locale.getDefault(), LibraryLoader.class.getClassLoader());

			Enumeration i = resources.getKeys();
			while (i.hasMoreElements()) {
				String key = (String) i.nextElement();
				keys.add(key);
			}

		} catch (MissingResourceException e) {
		}

		String path = System.getProperty("jacob.dll.path");
		if ((path == null) && (resources != null)
				&& (keys.contains("jacob.dll.path"))) {
			path = (String) resources.getObject("jacob.dll.path");
		}

		if (path != null) {
			System.load(path);
		} else {
			String name = null;

			if (System.getProperty("jacob.dll.name") != null)
				name = System.getProperty("jacob.dll.name");
			else if ((System.getProperty("jacob.dll.name.x86") != null)
					&& (shouldLoad32Bit())) {
				name = System.getProperty("jacob.dll.name.x86");
			} else if ((System.getProperty("jacob.dll.name.x64") != null)
					&& (!(shouldLoad32Bit()))) {
				name = System.getProperty("jacob.dll.name.x64");
			} else if ((resources != null) && (keys.contains("jacob.dll.name")))
				name = resources.getString("jacob.dll.name");
			else if ((resources != null)
					&& (keys.contains("jacob.dll.name.x86"))
					&& (shouldLoad32Bit())) {
				name = resources.getString("jacob.dll.name.x86");
			} else if ((resources != null)
					&& (keys.contains("jacob.dll.name.x64"))
					&& (!(shouldLoad32Bit()))) {
				name = resources.getString("jacob.dll.name.x64");
			} else {
				name = getPreferredDLLName();
			}
			System.loadLibrary(name);
			System.out.println("加载"+name+"成功!");
		}
	}

	public static String getPreferredDLLName() {
		if (shouldLoad32Bit()) {
			return "jacob-" + "1.15-M4" + "-" + "x86";
		}

		return "jacob-" + "1.15-M4" + "-" + "x64";
	}

	protected static boolean shouldLoad32Bit() {
		String bits = System.getProperty("sun.arch.data.model", "?");
		if (bits.equals("32"))
			return true;
		if (bits.equals("64")) {
			return false;
		}

		String arch = System.getProperty("java.vm.name", "?");

		return (arch.toLowerCase().indexOf("64-bit") < 0);
	}
}
